package com.ucampus.controller;

import com.ucampus.dao.ApiResponse;
import com.ucampus.entity.ResponseData;
import com.ucampus.entity.userinfo;
import com.ucampus.service.userinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 功能：
 * 作者： 启明星_Polaris
 * 日期：2024/12/26 下午10:39
 **/

@RestController
@RequestMapping("/users")
public class userinfoController {
    @Autowired
    private userinfoService userinfoService;

    // 获取所有用户
    @GetMapping
    public ApiResponse<List<userinfo>> getAllUsers() {
        List<userinfo> users = userinfoService.getAllUsers();
        return ApiResponse.success(users);
    }

    // 根据 ID 获取用户信息
    @GetMapping("/info")
    public ResponseEntity<ApiResponse<userinfo>> getUserById(@RequestParam long id) {
        userinfo user = userinfoService.getUserById(id);
        if(user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error("User not found"));
        }
        return ResponseEntity.ok(ApiResponse.success(user));
    }

    // 更新用户
    @PutMapping("/update")
    public ResponseEntity<ApiResponse<String>> updateUser(@RequestParam long id, @RequestBody userinfo user) {
        user.setId(id); // 确保更新的是正确的用户
        boolean isUpdated = userinfoService.updateUser(user);

        if (!isUpdated) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("Failed to update user!"));
        }
        userinfo updatedUser = userinfoService.getUserById(id);
        return ResponseEntity.ok(ApiResponse.success("User updated successfully!")) ;
    }

    // 根据 ID 删除用户
    @DeleteMapping("/delete")
    public String deleteUser(@RequestParam long id) {
        userinfoService.deleteUser(id);
        return "User deleted successfully!";
    }

    //管理员获取用户信息
    @GetMapping("/")
    public ResponseData getUsers(){
        return userinfoService.getUsers();
    }

    //管理员通过用户昵称模糊查询
    @GetMapping("/select")
    public ResponseData getUsersByName(@RequestParam("username") String username) {
        return userinfoService.getUsersByName(username);
    }

    //管理员修改用户账号状态
    @PutMapping("/updatestatus")
    public ResponseData updateStatus(@RequestBody List<Integer> list) {
        return userinfoService.updateStatus(list);
    }

    //管理员删除用户
    @DeleteMapping("/deleteuser")
    public ResponseData delete(@RequestBody List<Integer> list) {
        return userinfoService.delete(list);
    }
}
